package com.alm.token.utils;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.webkit.WebView;

import com.alm.token.R;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by nelson on 16/4/20.
 */
public class Utils {

    public static final String DATA_FORMAT_YYYY_MM_DD = "yyyy.MM.dd";
    public static final String DATA_FORMAT_YYYY_MM_DD_ = "yyyy-MM-dd";
    public static final String DATA_FORMAT_YYYY_MM_C = "yyyy年MM月";
    public static final String DATA_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy.MM.dd HH:mm:ss";
    public static final String DATA_FORMAT_YYYY_MM_DD_HH_MM = "yyyy/MM/dd HH:mm";
    public static final String DATA_FORMAT_DD_HH_MM = "dd HH:mm";
    public static final String DATA_FORMAT_HH_MM_SS = "HH:mm:ss";

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    /**
     * Create a file Uri for saving an image or video
     */
    public static Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * Create a File for saving an image or video
     */
    public static File getOutputMediaFile(int type) {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyCameraApp");

        // This location works best if you want the created images to be shared
        // between application
        // s and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metric = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metric);
        return metric.widthPixels;
    }

    public static SimpleDateFormat getSimpleDataFormat() {
        return new SimpleDateFormat(DATA_FORMAT_YYYY_MM_DD, Locale.getDefault());
    }

    public static SimpleDateFormat getSimpleDataFormat(String format) {
        return new SimpleDateFormat(format, Locale.getDefault());
    }

    public static DecimalFormat getSimpleDecimalFormat() {
        return new DecimalFormat("##0.00");
    }

    public static int dp2px(Context context, float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                context.getResources().getDisplayMetrics());
    }

    public static String UrlEncodeData(String data) {
        try {
            String d = URLEncoder.encode(data, "UTF-8");
            return d;
        } catch (UnsupportedEncodingException e) {
        }
        return data;
    }

    public static void destroyWebView(WebView webView) {
        if (webView != null) {
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }

            webView.stopLoading();
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.clearView();
            webView.removeAllViews();

            try {
                webView.destroy();
            } catch (Throwable ex) {

            }
        }
    }

    public static boolean isChinaPhoneLegal(String str)
            throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 根据区号判断是否是正确的电话号码
     * @param phoneNumber :带国家码的电话号码
     * @param countryCode :默认国家码
     * return ：true 合法  false：不合法
     */
    public static boolean isPhoneNumberValid(String phoneNumber, String countryCode){

        /**
         * boolean valid_cn = AndroidConfig.isPhoneNumberValid("+8615820799999","86");
         System.out.println("isPhoneNumberValid:"+valid_cn);

         boolean valid_hk = AndroidConfig.isPhoneNumberValid("+85283079901","852");
         System.out.println("isPhoneNumberValid:"+valid_hk);

         */
        System.out.println("isPhoneNumberValid: "+phoneNumber+"/"+countryCode);
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        try{
            Phonenumber.PhoneNumber numberProto = phoneUtil.parse(phoneNumber, countryCode);
            return phoneUtil.isValidNumber(numberProto);
        }catch (NumberParseException e){
            System.err.println("isPhoneNumberValid NumberParseException was thrown: " + e.toString());
        }
        return false;
    }

    /**
     * 校验输入的账号密码包含的字段是否符合规范
     * @param username_pasw 账号密码
     * return ：true 合法  false：不合法
     */
    public static boolean verifyUserName(String username_pasw){
        if (!username_pasw.matches("^+[A-Za-z0-9_\\.\\-]+$")) {
            return false;
        }
        return true;
    }

    /**
     * 校验输入的账号密码包含的字段是否符合规范
     * @param username_pasw 账号密码
     * return ：true 合法  false：不合法
     */
    public static boolean verifyUserPsw(String username_pasw){
        if (!username_pasw.matches("^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,20}$")) {
            return false;
        }
        return true;
    }

    /**
     * 校验输入的账号密码开头结尾是否符合规范
     *
     * @param username_pasw 账号密码
     *                      return ：true 合法  false：不合法
     */
    public static boolean verifyUserNameFL(String username_pasw) {
        //java.lang.character.isLetter();    断定指定字符是否是一个字母。
        //java.lang.character.isDigit();    确定或判断指定字符是否是一个数字。
        boolean flag = true;
        if (username_pasw.length() >= 2) {
            flag = (Character.isLetter(username_pasw.charAt(0)) || Character.isDigit(username_pasw.charAt(0))) &&
                    (Character.isLetter(username_pasw.charAt(username_pasw.length() - 1)) || Character.isDigit(username_pasw.charAt(username_pasw.length() - 1)));
        } else {
            flag = false;
        }
//        if (!username_pasw.matches("^[A-Za-z0-9][A-Za-z0-9_\\.\\-]+[A-Za-z0-9]$")) {
//            return false;
//        }
        return flag;
    }
}
